var ws = require('nodejs-websocket');
var port = 3000
let sum = 0

var server = ws.createServer(function (conn) {
    sum++
    conn.onload = sum
    let mes = {}
    mes.type = 'enter'
    mes.data = conn.onload + 'come'
    boardcast(JSON.stringify(mes))
    conn.on("text", function (str) {
        let mes = {}
        mes.type = 'message'
        mes.data = conn.onload + 'say:' + str
        boardcast(JSON.stringify(mes))
    })
    conn.on("close", function (code, reason) {
        sum--
        conn.onload = sum
        let mes = {}
        mes.type = 'leave'
        mes.data = conn.onload + 'close'
        boardcast(JSON.stringify(mes))
    })
    conn.on("error", function (err) {
        return false

    })
    function boardcast(str) {  // 广播 //
        server.connections.forEach(function (conn) {   //  .forEach 是调用数组里每个元素  //
            conn.sendText(str)
        })
    }
}).listen(port)
console.log("websocket server listen port is" + port)
